// DatabaseTask.cpp
#include "databasetask.h"
#include "db.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QDebug>
#include <QVariantMap>
#include <QVariantMap>

DatabaseTask::DatabaseTask(const QString& sql, const QVariantMap& params, const QString& type, QObject* parent)
    : QObject(parent), sql(sql),operationType(type), parameters(params)
{
    setAutoDelete(true);
}

// DatabaseTask.cpp
void DatabaseTask::run()
{
    QSqlDatabase db = DB::getInstance()->getConnection();

    if (!DB::getInstance()->isConnectionValid(db)) {
        emit error("无法打开数据库连接");
        return;
    }
    if(this->operationType == "登录")
        findData(db);
    else if(this->operationType == "注册")
        insertData(db);
}

void DatabaseTask::findData(QSqlDatabase& db)
{
    QSqlQuery query(db);
    if (!query.exec(sql)) {
        emit error(query.lastError().text());DB::getInstance()->releaseConnection(db);
        return;
    }

    QStringList result ;
    qDebug()<<sql<<endl;
    while (query.next()) {
        QString col0 = query.value(0).toString();
        QString col1 = query.value(1).toString();
        qDebug()<<QString("%1 %2").arg(col0, col1);
        result << QString("%1 %2").arg(col0, col1);
    }

    DB::getInstance()->releaseConnection(db);
    emit finished(result);
}

void DatabaseTask::insertData(QSqlDatabase& db)
{
    QSqlQuery query(db);
        query.prepare(sql);
        query.bindValue(":tms_gg", parameters["tms_gg"]);
        query.bindValue(":tms_user", parameters["tms_user"]);
        query.bindValue(":tms_password", parameters["tms_password"]);

        if (!query.exec()) {
            emit error(query.lastError().text());
            return;
        }

    DB::getInstance()->releaseConnection(db);
    emit finished({"执行成功"});
}
void DatabaseTask::setOperationType(const QString &type)
{
    this->operationType = type;
}

QString& DatabaseTask::getOperationType()
{
    return this->operationType;
}
